<?php
// 取消订单
// header("content-type:text/html;charset=utf-8");
include_once("conn.php");

//时区设置为中国
date_default_timezone_set('PRC');

//获取当前时间
$now = date('Y-m-d H:i:s');

$id = $_GET['id'];
$sql_select = "SELECT * FROM tb_order_info WHERE id='" . $id . "'";
$res_select = mysqli_query($conn, $sql_select);

if ($res_select) {
    if (mysqli_num_rows($res_select) > 0) {
        $row = mysqli_fetch_assoc($res_select);
        $sql_update_1 = "UPDATE tb_order_info SET o_status = -1, o_endtime = '" . $now . "' WHERE id='" . $id . "'";
        $sql_update_2 = "UPDATE tb_goods_info SET g_sell_num = g_sell_num - '" . $row['o_num'] . "' WHERE g_id='" . $row['g_id'] . "'";
        if ($row['o_status'] == 0) {
            //开启事务
            mysqli_autocommit($conn, false);
            $sql_arr = array($sql_update_1, $sql_update_2);
            $res_update = true;
            foreach ($sql_arr as $sql) {
                $res_update = mysqli_query($conn, $sql);
                if (!$res_update) {
                    break;
                }
            }
            if ($res_update) {
                //提交事务
                mysqli_commit($conn);
                echo "<script>alert('取消订单成功！');window.location.href='../u_show_order.php';</script>";
            } else {
                //回滚事务
                mysqli_rollback($conn);
                echo "<script>alert('取消失败请重试！');history.go(-1);</script>";
            }
        } else {
            echo "<script>alert('订单状态已改变！取消失败！');window.location.href='../u_show_order.php';</script>";
        }
    }
}